package eln.zaislu.muziejus;


import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.DisplayMetrics;
import android.util.FloatMath;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TimePicker;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;

public class ZaisluMuziejusActivity extends Activity implements View.OnTouchListener, AdapterView.OnItemLongClickListener
{
    /** Called when the activity is first created. */
	private static final String TAG = ZaisluMuziejusActivity.class.getSimpleName();
	private MainGamePanel gamepanel;
	private ImageButton bt1;
	private ImageButton bt2;
	private ImageButton bt3;
	private ImageButton trashButton;
	private ImageButton closeButton;
	private ImageButton reloadButton;
	private ImageButton backButton;
	private ImageButton actorsButton;
	private ImageButton toysButton;
	private ImageButton natureObjButton;
	private ImageButton backObjButton;
	private static View menuButt;
	private static View GallerySlider;
	private static View startupScreen;
	private static Animation slideUpIn;
	private static Animation slideUpOut;
	private static Animation slideLeft;
	private static Animation slideRight;
	private static Animation transparentAnim;
	private Gallery gallery;
	private Button butPrGal;
	private Button butNxGal;
	private static View frameDrag;
	private static RelativeLayout frame;
	int ItemsInGallery=0;
	 int CurrentIndex=0;
	 static int minGalObjectId=0;
	 static int maxGalObjectId=1;
	 
	 static final int backSTATE=1;
	 static final int actorsSTATE=2;		 
	 static final int toysSTATE=3;
	 static final int backObjSTATE=4;
	 static final int natureObjSTATE=5;
	 private int menuSTATE=backSTATE;
	 
	 
	 
	/*Integer pics[] = { R.drawable.dots, R.drawable.dots, R.drawable.dots, R.drawable.dots,
			R.drawable.dots,R.drawable.dots, R.drawable.dots, R.drawable.dots, R.drawable.dots,
			R.drawable.dots,R.drawable.dots, R.drawable.dots, R.drawable.dots, R.drawable.dots,
			R.drawable.dots };*/
	

    private static final int NOT_DRAGGING = 0;
    private static final int DRAGGING = 1;

    private static int state=NOT_DRAGGING;
    private static ImageView draggable =null;
    private static int dragged_position;
    static float current_x;
	static float current_y;
    int current_icon = R.drawable.avis;
    public static Context ctxx;

    public static SoundPool soundPool;
    public static int soundID;
    public static int soundLoop=0;
	boolean loaded = false;
	
	//These matrices will be used to move and zoom image
	Matrix matrix = new Matrix();
	Matrix savedMatrix = new Matrix();  

	// We can be in one of these 3 states
	static final int NONE = 0;
	static final int DRAG = 1;
	static final int ZOOM = 2;
	static final int DRAW =3;
	int mode = NONE;

	// Remember some things for zooming
	PointF start = new PointF();
	PointF mid = new PointF();
	float oldDist = 1f;

	// Limit zoomable/pannable image
	private float[] matrixValues = new float[9];
	private float maxZoom;
	private float minZoom;
	private float height;
	private float width;
	private RectF viewRect;
	private CountDownTimer lTimer;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        	        // making it full screen
        	        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        	       // getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        	        // set our MainGamePanel as the View
        	        requestWindowFeature(Window.FEATURE_NO_TITLE);
        	        //setContentView(R.layout.startup); 
        	        RelativeLayout relative = new RelativeLayout(this);
        	        gamepanel=new MainGamePanel(this);
        	        relative.addView(gamepanel);
        	        slideUpIn = AnimationUtils.loadAnimation(this, R.anim.slide_up);
        	        slideUpOut = AnimationUtils.loadAnimation(this, R.anim.slide_down);
        	        slideLeft = AnimationUtils.loadAnimation(this, R.anim.slide_left);
        	        slideRight = AnimationUtils.loadAnimation(this, R.anim.slide_right);
        	        transparentAnim = AnimationUtils.loadAnimation(this, R.anim.transparent);
        	        gamepanel.setOnLongClickListener(longClick);
        	        
        	       // startupScreen=View.inflate(getBaseContext(),R.layout.startup,null);
        	       // relative.addView(startupScreen);
        	        
        	        menuButt=View.inflate(getBaseContext(),R.layout.buttons,null);
        	        relative.addView(menuButt);
        	        GallerySlider=View.inflate(getBaseContext(),R.layout.imgslider,null);
        	        relative.addView(GallerySlider);
        	        frameDrag=View.inflate(getBaseContext(),R.layout.draglayout,null);
        	        relative.addView(frameDrag);
        	        
        	       
        	                         
        	        setContentView(relative); 
        	        ctxx=getBaseContext();
        	        findAllViewsById();
        	        
        	        //setContentView(new MainGamePanel(this));
        	        //Log.d(TAG, "View added");
        	        
        	        this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
        		    // Load the sound
        		    soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
        		    soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
        		      public void onLoadComplete(SoundPool soundPool, int sampleId,
        		          int status) {
        		        loaded = true;
        		        AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        			      float actualVolume = (float) audioManager
        			          .getStreamVolume(AudioManager.STREAM_MUSIC);
        			      float maxVolume = (float) audioManager
        			          .getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        			      float volume = actualVolume / maxVolume;
        		       if (loaded) {
        		    	  // soundPool.play(soundID, volume, volume, 1, 0, 1f);
        			        soundPool.play(soundID, volume, volume, 1, soundLoop, 1f);
        			      }
        		      }
        		    });
        	        
        	        lTimer = new CountDownTimer(3000, 1000) {
        	            public void onFinish() {
        	            	//onLoad();
        	            }
        	            @Override
        	            public void onTick(long millisUntilFinished) {
        	                // TODO Auto-generated method stub
        	            }
        	        }.start();
        	        
            	    
    }
    
    private void onLoad() {
    	startupScreen.startAnimation(transparentAnim);
    	startupScreen.setVisibility(View.GONE);
    }
    
     
    private void findAllViewsById() {
    	
    	bt1 = (ImageButton) findViewById(R.id.imageButton1);
        bt1.setOnClickListener(callButtonListener1);
        bt2 = (ImageButton) findViewById(R.id.imageButton2);
        bt2.setOnClickListener(callButtonListener2);
        bt3 = (ImageButton) findViewById(R.id.imageButton3);
        bt3.setOnClickListener(callButtonListener3);
        bt1.setVisibility(View.GONE);
        bt2.setVisibility(View.GONE);
        bt3.setVisibility(View.GONE);
        
        trashButton = (ImageButton) findViewById(R.id.imageButton5);
        trashButton.setOnClickListener(callDeleteObject);
        
        closeButton = (ImageButton) findViewById(R.id.closeButton);
        closeButton.setOnClickListener(callCloseObject);
        
        reloadButton = (ImageButton) findViewById(R.id.imageButton6);
        reloadButton.setOnClickListener(callRefreshObject);
        
        backButton = (ImageButton) findViewById(R.id.backButton);
        backButton.setOnClickListener(callbackButton);
    	actorsButton = (ImageButton) findViewById(R.id.actorsButton);
    	actorsButton.setOnClickListener(callactorsButton);
    	toysButton = (ImageButton) findViewById(R.id.toysButton);
    	toysButton.setOnClickListener(calltoysButton);
    	natureObjButton = (ImageButton) findViewById(R.id.natureObjButton);
    	natureObjButton.setOnClickListener(callnatureObjButton);
    	backObjButton = (ImageButton) findViewById(R.id.backObjButton);
    	backObjButton.setOnClickListener(callbackObjButton);
    	//backButton.setImageResource(R.drawable.aplinkos_blue_btn);  
       // butPrGal = (Button) findViewById(R.id.btnPrev);
       // butPrGal.setOnClickListener(onClickGalBut); 
       // butNxGal = (Button) findViewById(R.id.btnNext);
        //butNxGal.setOnClickListener(onClickGalBut); 
        
        gallery = (Gallery) findViewById(R.id.Gallery01);
        minGalObjectId=0;
        maxGalObjectId=4;
        gallery.setLongClickable(false);
		gallery.setAdapter(new ImageAdapter(this,MainGamePanel.objects,minGalObjectId,maxGalObjectId));
		gallery.setOnTouchListener(new View.OnTouchListener(){

			public boolean onTouch(View v, MotionEvent event) {
				if (state == DRAGGING) {
		            Log.d(TAG, "already have an object moving... ?");
		            return false;
		        }
                
				
				RelativeLayout frame = (RelativeLayout) findViewById(R.id.DraggingLayoutMain);
		        int frame_position[] = new int[2];
		        frame.getLocationOnScreen(frame_position);

		        // setup everything for dragging
		        state = DRAGGING;
		        mode = DRAG;
		        dragged_position = minGalObjectId+2;

		        draggable = new ImageView(ctxx);
		        Bitmap bm =v.getDrawingCache();
		        
		        final BitmapFactory.Options options = new BitmapFactory.Options();
				 options.inJustDecodeBounds = true;
				 BitmapFactory.decodeResource(getResources(), MainGamePanel.objects.get(dragged_position).icon, options);
				 options.inSampleSize = MainGamePanel.calculateInSampleSize(options, 200, 200);
				 options.inJustDecodeBounds = false;
				bm=BitmapFactory.decodeResource(getResources(), MainGamePanel.objects.get(dragged_position).icon, options);//BitmapFactory.decodeResource(getResources(), objects.get(resint).image);
				 
		        bm=Bitmap.createScaledBitmap(bm, 200, 200, true);
		        draggable.setImageBitmap(bm);
		        draggable.setAlpha(150);
		        draggable.setScaleType(ImageView.ScaleType.CENTER);
		        draggable.setPadding((int) current_x-frame_position[0]-(bm.getWidth()/2), (int) current_y-frame_position[1]-(bm.getHeight()/2), 0, 0);

		        frame.setVisibility(View.VISIBLE);
		        frame.addView(draggable, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

				return false;
			}});
		gallery.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
			/*	if (state == DRAGGING) {
		            Log.d(TAG, "already have an object moving... ?");
		            //return false;
		        }
                
				
				RelativeLayout frame = (RelativeLayout) findViewById(R.id.DraggingLayoutMain);
		        int frame_position[] = new int[2];
		        frame.getLocationOnScreen(frame_position);

		        // setup everything for dragging
		        state = DRAGGING;
		        mode = DRAG;
		        dragged_position = minGalObjectId+arg2;

		        draggable = new ImageView(ctxx);
		        Bitmap bm =arg1.getDrawingCache();
		        
		        final BitmapFactory.Options options = new BitmapFactory.Options();
				 options.inJustDecodeBounds = true;
				 BitmapFactory.decodeResource(getResources(), MainGamePanel.objects.get(dragged_position).icon, options);
				 options.inSampleSize = MainGamePanel.calculateInSampleSize(options, 200, 200);
				 options.inJustDecodeBounds = false;
				bm=BitmapFactory.decodeResource(getResources(), MainGamePanel.objects.get(dragged_position).icon, options);//BitmapFactory.decodeResource(getResources(), objects.get(resint).image);
				 
		        bm=Bitmap.createScaledBitmap(bm, 200, 200, true);
		        draggable.setImageBitmap(bm);
		        draggable.setAlpha(150);
		        draggable.setScaleType(ImageView.ScaleType.CENTER);
		        draggable.setPadding((int) current_x-frame_position[0]-(bm.getWidth()/2), (int) current_y-frame_position[1]-(bm.getHeight()/2), 0, 0);

		        frame.setVisibility(View.VISIBLE);
		        frame.addView(draggable, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
*/
				
				//this.onItemLongClick(arg0,arg1,arg2,arg3);
		/*		RelativeLayout frame = (RelativeLayout) findViewById(R.id.DraggingLayoutMain);
		        int frame_position[] = new int[2];
		        frame.getLocationOnScreen(frame_position);

		        // setup everything for dragging
		        state = DRAGGING;
		        dragged_position = minGalObjectId+arg2;

		        draggable = new ImageView(ctxx);
		        Bitmap bm =arg1.getDrawingCache();
		        
		        final BitmapFactory.Options options = new BitmapFactory.Options();
				 options.inJustDecodeBounds = true;
				 BitmapFactory.decodeResource(getResources(), MainGamePanel.objects.get(dragged_position).icon, options);
				 options.inSampleSize = MainGamePanel.calculateInSampleSize(options, 200, 200);
				 options.inJustDecodeBounds = false;
				bm=BitmapFactory.decodeResource(getResources(), MainGamePanel.objects.get(dragged_position).icon, options);//BitmapFactory.decodeResource(getResources(), objects.get(resint).image);
				 
		        //bm=BitmapFactory.decodeResource(getResources(), MainGamePanel.objects.get(dragged_position).icon);
		       // int wd=bm.getHeight();
		        bm=Bitmap.createScaledBitmap(bm, 200, 200, true);
		        //wd=bm.getHeight();
		        draggable.setImageBitmap(bm);
		        draggable.setAlpha(150);
		        draggable.setScaleType(ImageView.ScaleType.CENTER);
		       // draggable.setDrawingCacheEnabled(true);
		        draggable.setPadding((int) current_x-frame_position[0]-(bm.getWidth()/2), (int) current_y-frame_position[1]-(bm.getHeight()/2), 0, 0);

		        frame.setVisibility(View.VISIBLE);
		        frame.addView(draggable, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
*/
				//GallerySlider.startAnimation(slideRight);
				//GallerySlider.setVisibility(View.GONE);
				
				 //--selectItemInGalerry(arg2);
				//AlphaAnimation alpha = new AlphaAnimation(0.0F, 0.0F);
                //alpha.setDuration(3000); // Make animation instant
                //alpha.setFillAfter(true); // Tell it to persist after the animation ends
                // And then on your layout
                //GallerySlider.startAnimation(alpha);
				
			}

			
		});
		gallery.setOnItemLongClickListener(this);
		
		gallery.setOnTouchListener(this);
		//gallery.setSelection(4);
		DisplayMetrics metrics = new DisplayMetrics();
		getWindow().getWindowManager().getDefaultDisplay().getMetrics(metrics);

		MarginLayoutParams mlp = (MarginLayoutParams) gallery.getLayoutParams();
		mlp.setMargins((int) -(metrics.widthPixels-180), mlp.topMargin, mlp.rightMargin, mlp.bottomMargin);
				
		Display display=getWindowManager().getDefaultDisplay();
		//int wid=display.getWidth()-butPrGal.getWidth()-butNxGal.getWidth();
		//LinearLayout.LayoutParams galleryParams = new LinearLayout.LayoutParams(wid, LayoutParams.FILL_PARENT);
		//gallery.setLayoutParams(galleryParams);

		RelativeLayout frameGallery = (RelativeLayout) findViewById(R.id.InnerRelativeLayoutGallery);
		frameGallery.setVisibility(View.GONE);
		RelativeLayout frameMain = (RelativeLayout) findViewById(R.id.InnerRelativeLayoutMain);
		frameMain.setVisibility(View.GONE);
		frame = (RelativeLayout) findViewById(R.id.DraggingLayoutMain);
		frame.setVisibility(View.GONE);
    }
    
    private OnClickListener callDeleteObject = new OnClickListener() {
        public void onClick(View v) {
        	try{
        		if (MainGamePanel.deleteStatus){
        			MainGamePanel.deleteStatus=false;
        			trashButton.setImageResource(R.drawable.trintukas);
        		}else{
        			MainGamePanel.deleteStatus=true;
        			trashButton.setImageResource(R.drawable.trintukas_blue);
        		}
        	/*for(int i=0;i<MainGamePanel.imo.size();i++){
				   if (MainGamePanel.imo.get(i).isTouched()){
					   MainGamePanel.imo.remove(i);
				   }
        	}*/
        	}catch(Exception ex){}
        }
    };
    
    private OnClickListener callCloseObject = new OnClickListener() {
        public void onClick(View v) {
            	MainGamePanel.thread.setRunning(false);
            	finish();
        }
    };
    
    private OnClickListener callRefreshObject = new OnClickListener() {
        public void onClick(View v) {
        	//Context ctx=getBaseContext();
        	 AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(ZaisluMuziejusActivity.this);
        	 myAlertDialog.setTitle("Įspėjimas");
        	 myAlertDialog.setMessage("Ar tikrai norite viską ištrinti?");
        	 myAlertDialog.setPositiveButton("Taip", new DialogInterface.OnClickListener() {

        	  public void onClick(DialogInterface arg0, int arg1) {
        	     // do something when the OK button is clicked
        		  try{
              		MainGamePanel.imo.clear();
                	}catch(Exception ex){}
        	  }});
        	 myAlertDialog.setNegativeButton("Ne", new DialogInterface.OnClickListener() {
        	       
        	  public void onClick(DialogInterface arg0, int arg1) {
        	  // do something when the Cancel button is clicked
        	  }});
        	 myAlertDialog.show();
        	
        	
        }
    };
    
    private OnClickListener callbackButton = new OnClickListener() {
        public void onClick(View v) {
            bt1.setVisibility(View.VISIBLE);
            bt2.setVisibility(View.VISIBLE);
            bt3.setVisibility(View.VISIBLE);
            bt1.setImageResource(R.drawable.viduramziai_button_states);    
            bt2.setImageResource(R.drawable.etnografija_button_states);    
            bt3.setImageResource(R.drawable.siandien_button_states); 
            backButton.setImageResource(R.drawable.aplinkos_blue_btn);    
            actorsButton.setImageResource(R.drawable.actors_button_states);    
            toysButton.setImageResource(R.drawable.toys_button_states);   
            backObjButton.setImageResource(R.drawable.backobj_button_states);   
            natureObjButton.setImageResource(R.drawable.natureobj_button_states);   
            menuSTATE=backSTATE;
            if (GallerySlider.getVisibility() == View.VISIBLE){
            GallerySlider.startAnimation(slideRight);
			GallerySlider.setVisibility(View.GONE);
            }
        }
    };
    
    private OnClickListener callactorsButton = new OnClickListener() {
        public void onClick(View v) {
        	bt1.setVisibility(View.VISIBLE);
            bt2.setVisibility(View.VISIBLE);
            bt3.setVisibility(View.VISIBLE);
            bt1.setImageResource(R.drawable.viduramziai_button_states);    
            bt2.setImageResource(R.drawable.etnografija_button_states);    
            bt3.setImageResource(R.drawable.siandien_button_states); 
            backButton.setImageResource(R.drawable.back_button_states);    
            actorsButton.setImageResource(R.drawable.veikejai_blue_btn);    
            toysButton.setImageResource(R.drawable.toys_button_states);   
            backObjButton.setImageResource(R.drawable.backobj_button_states);   
            natureObjButton.setImageResource(R.drawable.natureobj_button_states);   
            menuSTATE=actorsSTATE;
            if (GallerySlider.getVisibility() == View.VISIBLE){
            GallerySlider.startAnimation(slideRight);
			GallerySlider.setVisibility(View.GONE);
            }
        }
    };
    
    private OnClickListener calltoysButton = new OnClickListener() {
        public void onClick(View v) {
        	bt1.setVisibility(View.VISIBLE);
            bt2.setVisibility(View.VISIBLE);
            bt3.setVisibility(View.VISIBLE);
            bt1.setImageResource(R.drawable.viduramziai_button_states);    
            bt2.setImageResource(R.drawable.etnografija_button_states);    
            bt3.setImageResource(R.drawable.siandien_button_states); 
            backButton.setImageResource(R.drawable.back_button_states);    
            actorsButton.setImageResource(R.drawable.actors_button_states);    
            toysButton.setImageResource(R.drawable.zaislai_blue_btn);   
            backObjButton.setImageResource(R.drawable.backobj_button_states);   
            natureObjButton.setImageResource(R.drawable.natureobj_button_states);  
            menuSTATE=toysSTATE;
            if (GallerySlider.getVisibility() == View.VISIBLE){
            GallerySlider.startAnimation(slideRight);
			GallerySlider.setVisibility(View.GONE);
            }
        }
    };
    
    private OnClickListener callbackObjButton = new OnClickListener() {
        public void onClick(View v) {
        	bt1.setVisibility(View.GONE);
            bt2.setVisibility(View.GONE);
            bt3.setVisibility(View.GONE);
            backButton.setImageResource(R.drawable.back_button_states);    
            actorsButton.setImageResource(R.drawable.actors_button_states);    
            toysButton.setImageResource(R.drawable.toys_button_states);   
            backObjButton.setImageResource(R.drawable.aplinkos_objektai_blue_btn);   
            natureObjButton.setImageResource(R.drawable.natureobj_button_states); 
            menuSTATE=backObjSTATE;
            
            minGalObjectId=77;
	        maxGalObjectId=14;
			gallery.setAdapter(new ImageAdapter(ctxx,MainGamePanel.objects,minGalObjectId,maxGalObjectId));
			//gallery.setSelection(3);
			GallerySlider.startAnimation(slideLeft);
			GallerySlider.setVisibility(View.VISIBLE);
        }
    };
    
    private OnClickListener callnatureObjButton = new OnClickListener() {
        public void onClick(View v) {
        	bt1.setVisibility(View.GONE);
            bt2.setVisibility(View.GONE);
            bt3.setVisibility(View.GONE);
            backButton.setImageResource(R.drawable.back_button_states);    
            actorsButton.setImageResource(R.drawable.actors_button_states);    
            toysButton.setImageResource(R.drawable.toys_button_states);   
            backObjButton.setImageResource(R.drawable.backobj_button_states);   
            natureObjButton.setImageResource(R.drawable.gamtos_objektai_blue_btn);  
            menuSTATE=natureObjSTATE;
            
            minGalObjectId=67;
	        maxGalObjectId=10;
			gallery.setAdapter(new ImageAdapter(ctxx,MainGamePanel.objects,minGalObjectId,maxGalObjectId));
			//gallery.setSelection(3);
			GallerySlider.startAnimation(slideLeft);
			GallerySlider.setVisibility(View.VISIBLE);
        }
    };
    
    public void selectItemInGalerry(int arg2) {
		// TODO Auto-generated method stub
		final int iPosition = arg2;

        if (iPosition != AdapterView.INVALID_POSITION)
        {
            //this is necessary to obtain the index of the view currently visible and pressed
            final int iVisibleViewIndex = iPosition - gallery.getFirstVisiblePosition();

            //get a reference to the child and modify the border
            for(int i=0;i<gallery.getChildCount();i++){
           	 View child = gallery.getChildAt(i);
                if (child != null)
                {
                    RelativeLayout borderImg = (RelativeLayout)child;
                    borderImg.setBackgroundColor(0x88000000);
                    View child1 = borderImg.getChildAt(0);
                    child1.setBackgroundColor(0x88000000);
                }
            }
            View child = gallery.getChildAt(iVisibleViewIndex);
            if (child != null)
            {
                RelativeLayout borderImg = (RelativeLayout)child;
                borderImg.setBackgroundColor(0xFFFF0000);
                View child1 = borderImg.getChildAt(0);
                child1.setBackgroundColor(0x88000000);
            }
        }
	}
     
    private OnClickListener onClickGalBut = new OnClickListener() {
    public void onClick(View v) {
     // TODO Auto-generated method stub
   /*  switch(v.getId())
     {
     case R.id.btnNext:
      //Increase the index
    	 ItemsInGallery=gallery.getCount();
      CurrentIndex++;
      //if reached the end of the gallery, then start from the first item
      if(CurrentIndex>ItemsInGallery-1)
       CurrentIndex=0;
      gallery.setSelection(CurrentIndex,true);
      selectItemInGalerry(CurrentIndex);
      break;
     case R.id.btnPrev:
      //Decrease the index
    	 ItemsInGallery=gallery.getCount();
      CurrentIndex=CurrentIndex-1;
      //If reached the first item, then return to the last item in the gallery
      if(CurrentIndex<0)
       CurrentIndex=ItemsInGallery-1;
      gallery.setSelection(CurrentIndex,true);
      selectItemInGalerry(CurrentIndex);
      //gallery.getS
      break;
     }*/
    }
    };
       
    @Override
    	 protected void onDestroy() {
    	  Log.d(TAG, "Destroying...");
    	  super.onDestroy();
    	 }
    	 
    	 @Override
    	 protected void onStop() {
    	  Log.d(TAG, "Stopping...");
    	  super.onStop();
    	 }
    	 
        	 private OnClickListener callButtonListener1 = new OnClickListener() {
    			public void onClick(View arg0) {
    				//((Activity)getBaseContext()).finish();
    				bt1.setImageResource(R.drawable.viduramziai_blue);    
                    bt2.setImageResource(R.drawable.etnografija_button_states);    
                    bt3.setImageResource(R.drawable.siandien_button_states); 
    				 switch (menuSTATE) {
    	                case backSTATE:
    	                	
    	                	gamepanel.changeBack(0);
    	                	playSound(gamepanel.objects.get(0).soundid,0);
    	                    break;
    	                case actorsSTATE:
    	                	minGalObjectId=3;
    	    		        maxGalObjectId=10;
    	    				gallery.setAdapter(new ImageAdapter(ctxx,MainGamePanel.objects,minGalObjectId,maxGalObjectId));
    	    				//gallery.setSelection(3);
    	    				GallerySlider.startAnimation(slideLeft);
    	    				GallerySlider.setVisibility(View.VISIBLE);
    	                    break;  
    	                case toysSTATE:
    	                	minGalObjectId=29;
    	    		        maxGalObjectId=16;
    	    				gallery.setAdapter(new ImageAdapter(ctxx,MainGamePanel.objects,minGalObjectId,maxGalObjectId));
    	    				//gallery.setSelection(3);
    	    				GallerySlider.startAnimation(slideLeft);
    	    				GallerySlider.setVisibility(View.VISIBLE);
    	                    break;   
    				 }
    				//menuButt.startAnimation(slideUpIn);
    				//menuButt.setVisibility(View.VISIBLE);
    			}
    		};
    		private OnClickListener callButtonListener2 = new OnClickListener() {
    			public void onClick(View arg0) {
    				//menuButt.startAnimation(slideUpOut);
    				//menuButt.setVisibility(View.GONE);
    				bt1.setImageResource(R.drawable.viduramziai_button_states);    
                    bt2.setImageResource(R.drawable.etnografija_blue);    
                    bt3.setImageResource(R.drawable.siandien_button_states); 
    				switch (menuSTATE) {
	                case backSTATE:
	                	gamepanel.changeBack(1);
	                	playSound(gamepanel.objects.get(1).soundid,0);
	                    break;
	                case actorsSTATE:
	                	minGalObjectId=13;
	    		        maxGalObjectId=8;
	    				gallery.setAdapter(new ImageAdapter(ctxx,MainGamePanel.objects,minGalObjectId,maxGalObjectId));
	    				//gallery.setSelection(3);
	    				GallerySlider.startAnimation(slideLeft);
	    				GallerySlider.setVisibility(View.VISIBLE);
	                    break;  
	                case toysSTATE:
	                	minGalObjectId=45;
	    		        maxGalObjectId=12;
	    				gallery.setAdapter(new ImageAdapter(ctxx,MainGamePanel.objects,minGalObjectId,maxGalObjectId));
	    				//gallery.setSelection(3);
	    				GallerySlider.startAnimation(slideLeft);
	    				GallerySlider.setVisibility(View.VISIBLE);
	                    break;   
				 }
    				
    				/*minGalObjectId=4;
    		        maxGalObjectId=20;
    				gallery.setAdapter(new ImageAdapter(ctxx,MainGamePanel.objects,minGalObjectId,maxGalObjectId));
    				gallery.setSelection(3);
    				GallerySlider.startAnimation(slideLeft);
    				GallerySlider.setVisibility(View.VISIBLE);*/
    			}
    		};
    		private OnClickListener callButtonListener3 = new OnClickListener() {
    			public void onClick(View arg0) {
    				//((Activity)getBaseContext()).finish();
    				bt1.setImageResource(R.drawable.viduramziai_button_states);    
                    bt2.setImageResource(R.drawable.etnografija_button_states);    
                    bt3.setImageResource(R.drawable.siandien_blue); 
    				switch (menuSTATE) {
	                case backSTATE:
	                	gamepanel.changeBack(2);
	                	playSound(gamepanel.objects.get(2).soundid,0);
	                    break;
	                case actorsSTATE:
	                	minGalObjectId=21;
	    		        maxGalObjectId=8;
	    				gallery.setAdapter(new ImageAdapter(ctxx,MainGamePanel.objects,minGalObjectId,maxGalObjectId));
	    				//gallery.setSelection(3);
	    				GallerySlider.startAnimation(slideLeft);
	    				GallerySlider.setVisibility(View.VISIBLE);
	                    break;  
	                case toysSTATE:
	                	minGalObjectId=57;
	    		        maxGalObjectId=10;
	    				gallery.setAdapter(new ImageAdapter(ctxx,MainGamePanel.objects,minGalObjectId,maxGalObjectId));
	    				//gallery.setSelection(3);
	    				GallerySlider.startAnimation(slideLeft);
	    				GallerySlider.setVisibility(View.VISIBLE);
	                    break;   
				 }
    				
    				/*minGalObjectId=21;
    		        maxGalObjectId=40;
    				gallery.setAdapter(new ImageAdapter(ctxx,MainGamePanel.objects,minGalObjectId,maxGalObjectId));
    				gallery.setSelection(3);
    				GallerySlider.startAnimation(slideLeft);
    				GallerySlider.setVisibility(View.VISIBLE);*/
    			}
    		};
    		
    		private OnLongClickListener longClick = new OnLongClickListener() {
    			public boolean onLongClick(View arg0) {
    				menuButt.startAnimation(slideUpIn);
    				return true;
    			}
    		};
    		
    		public static void callMenu(){
    			menuButt.startAnimation(slideUpIn);
    			menuButt.setVisibility(View.VISIBLE);
    			
    			
    		}
    		
    		public static void hideMenu(){
    			if (GallerySlider.getVisibility()==View.VISIBLE){
    			  GallerySlider.startAnimation(slideRight);
				  GallerySlider.setVisibility(View.GONE);
    			}
    			if (menuButt.getVisibility()==View.VISIBLE){
    			  menuButt.startAnimation(slideUpOut);
				  menuButt.setVisibility(View.GONE);
    			}
    		}
    		
    		

			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				if (state == DRAGGING) {
		            Log.d(TAG, "already have an object moving... ?");
		            return false;
		        }
                
				
				RelativeLayout frame = (RelativeLayout) findViewById(R.id.DraggingLayoutMain);
		        int frame_position[] = new int[2];
		        frame.getLocationOnScreen(frame_position);

		        // setup everything for dragging
		        state = DRAGGING;
		        mode = DRAG;
		        dragged_position = minGalObjectId+arg2;

		        draggable = new ImageView(this);
		        Bitmap bm =arg1.getDrawingCache();
		        
		        final BitmapFactory.Options options = new BitmapFactory.Options();
				 options.inJustDecodeBounds = true;
				 BitmapFactory.decodeResource(getResources(), MainGamePanel.objects.get(dragged_position).icon, options);
				 options.inSampleSize = MainGamePanel.calculateInSampleSize(options, 200, 200);
				 options.inJustDecodeBounds = false;
				bm=BitmapFactory.decodeResource(getResources(), MainGamePanel.objects.get(dragged_position).icon, options);//BitmapFactory.decodeResource(getResources(), objects.get(resint).image);
				 
		        //bm=BitmapFactory.decodeResource(getResources(), MainGamePanel.objects.get(dragged_position).icon);
		       // int wd=bm.getHeight();
		        bm=Bitmap.createScaledBitmap(bm, 200, 200, true);
		        //wd=bm.getHeight();
		        draggable.setImageBitmap(bm);
		        draggable.setAlpha(150);
		        draggable.setScaleType(ImageView.ScaleType.CENTER);
		       // draggable.setDrawingCacheEnabled(true);
		        draggable.setPadding((int) current_x-frame_position[0]-(bm.getWidth()/2), (int) current_y-frame_position[1]-(bm.getHeight()/2), 0, 0);

		        frame.setVisibility(View.VISIBLE);
		        frame.addView(draggable, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

				return false;
			}
			
			public boolean onTouch(View arg0, MotionEvent me) {
				// TODO Auto-generated method stub
				//if (state == NOT_DRAGGING) {
				if ((state == NOT_DRAGGING)&&(mode!=ZOOM)) {
		            // get the position of the touch so we know where to place the dragging item if it is a long press
		            current_x = me.getRawX();
		            current_y = me.getRawY();
		          
		            return false;
		        }
		        else {
		        	/*RelativeLayout frame = (RelativeLayout) findViewById(R.id.DraggingLayoutMain);
                    
		            if (me.getAction()==MotionEvent.ACTION_UP) {
		            	//cia iteroiam po numetimo
		                
		                int frame_position[] = new int[2];
		                frame.getLocationOnScreen(frame_position);
		                int xf=(int) me.getRawX()-frame_position[0];//-(draggable.getDrawable().getIntrinsicWidth()/2);
		                int yf =(int) me.getRawY()-frame_position[1];//-(draggable.getDrawable().getIntrinsicHeight()/2);
		                me.setLocation(xf,yf);
		                gamepanel.onTouchEvent(me,arg0,dragged_position);
		                frame.removeAllViews();
		            	draggable.setAlpha(255);
		                draggable=null;
		                
		                frame.setVisibility(View.GONE);
		                state=NOT_DRAGGING;
		                
		               playSound(gamepanel.objects.get(dragged_position).soundid);

		               
		            }
		            if (me.getAction()==MotionEvent.ACTION_MOVE) {
		            	 
		                int frame_position[] = new int[2];
		                frame.getLocationOnScreen(frame_position);

		                draggable.setPadding(
		                        (int) me.getRawX()-frame_position[0]-(draggable.getDrawable().getIntrinsicWidth()/2),
		                        (int) me.getRawY()-frame_position[1]-(draggable.getDrawable().getIntrinsicHeight()/2),
		                        0, 0);
		                draggable.invalidate();

		            }*/
		        }
				
				RelativeLayout frame = (RelativeLayout) findViewById(R.id.DraggingLayoutMain);
				int frame_position[]= new int[2];
		       // Handle touch events here...
			    switch (me.getAction() & MotionEvent.ACTION_MASK) {
			    case MotionEvent.ACTION_DOWN:
			        savedMatrix.set(matrix);
			        start.set(me.getX(), me.getY());
			        Log.d(TAG, "mode=DRAG");
			        mode = DRAG;
			        break;
			    case MotionEvent.ACTION_POINTER_DOWN:
			    	/*Context context = getApplicationContext();
		            CharSequence text = "ACTION_POINTER_DOWN!";
		            int duration = Toast.LENGTH_SHORT;

		            Toast toast = Toast.makeText(context, text, duration);
		            toast.show();*/
			        oldDist = spacing(me);
			        Log.d(TAG, "oldDist=" + oldDist);
			        if (oldDist > 10f) {
			            savedMatrix.set(matrix);
			            midPoint(mid, me);
			            mode = ZOOM;
			            Log.d(TAG, "mode=ZOOM");
			            
			            
			        }
			        break;
			    case MotionEvent.ACTION_UP:
			    /*	Context context1 = getApplicationContext();
		            CharSequence text1 = "ACTION_UP!";
		            int duration1 = Toast.LENGTH_SHORT;

		            Toast toast1 = Toast.makeText(context1, text1, duration1);
		            toast1.show();*/
			    	//frame_position[] = new int[2];
	                frame.getLocationOnScreen(frame_position);
	                int xf=(int) me.getRawX()-frame_position[0];//-(draggable.getDrawable().getIntrinsicWidth()/2);
	                int yf =(int) me.getRawY()-frame_position[1];//-(draggable.getDrawable().getIntrinsicHeight()/2);
	                me.setLocation(xf,yf);
	                gamepanel.onTouchEvent(me,arg0,dragged_position);
	                frame.removeAllViews();
	            	draggable.setAlpha(255);
	                draggable=null;
	                
	                frame.setVisibility(View.GONE);
	                state=NOT_DRAGGING;
	               // mode=NONE;
	                 playSound(gamepanel.objects.get(dragged_position).soundid,0);
	               //break;
			    case MotionEvent.ACTION_POINTER_UP:
			        mode = NONE;
			        Log.d(TAG, "mode=NONE");
			        break;
			    case MotionEvent.ACTION_MOVE:
			        if (mode == DRAW){ onTouchEvent(me);}
			        if (mode == DRAG) {
			        	   // frame_position[] = new int[2];
			                frame.getLocationOnScreen(frame_position);

			                draggable.setPadding(
			                        (int) me.getRawX()-frame_position[0]-(draggable.getDrawable().getIntrinsicWidth()/2),
			                        (int) me.getRawY()-frame_position[1]-(draggable.getDrawable().getIntrinsicHeight()/2),
			                        0, 0);
			                draggable.invalidate();  
			        } 
			     else if (mode == ZOOM) {
			         float newDist = spacing(me);
			         Log.d(TAG, "newDist=" + newDist);
			         if (newDist > 10f) {
			             matrix.set(savedMatrix);
			             float scale = newDist / oldDist;
			             matrix.getValues(matrixValues);
			             float currentScale = matrixValues[Matrix.MSCALE_X];
			             // limit zoom
			             if (scale * currentScale > maxZoom) {
			                 scale = maxZoom / currentScale; 
			                }else if(scale * currentScale < minZoom){
			                    scale = minZoom / currentScale; 
			                 }
			             matrix.postScale(scale, scale, mid.x, mid.y);
			            }
			         draggable.setImageMatrix(matrix);
			     }
			     break;
			    }
			    
				
				
		            return true;
				
				/*if (state == DRAGGING) {
		            Log.d(TAG, "already have an object moving... ?");
		            return false;
		        }
             	RelativeLayout frame = (RelativeLayout) findViewById(R.id.DraggingLayoutMain);
		        int frame_position[] = new int[2];
		        frame.getLocationOnScreen(frame_position);
                state = DRAGGING;
		        dragged_position = minGalObjectId+dragged_position;
		        draggable = new ImageView(this);
		        Bitmap bm =arg0.getDrawingCache();
		        final BitmapFactory.Options options = new BitmapFactory.Options();
				 options.inJustDecodeBounds = true;
				 BitmapFactory.decodeResource(getResources(), MainGamePanel.objects.get(dragged_position).icon, options);
				 options.inSampleSize = MainGamePanel.calculateInSampleSize(options, 200, 200);
				 options.inJustDecodeBounds = false;
				bm=BitmapFactory.decodeResource(getResources(), MainGamePanel.objects.get(dragged_position).icon, options);//BitmapFactory.decodeResource(getResources(), objects.get(resint).image);
		        bm=Bitmap.createScaledBitmap(bm, 200, 200, true);
		        draggable.setImageBitmap(bm);
		        draggable.setAlpha(150);
		        draggable.setScaleType(ImageView.ScaleType.CENTER);
		       draggable.setPadding((int) current_x-frame_position[0]-(bm.getWidth()/2), (int) current_y-frame_position[1]-(bm.getHeight()/2), 0, 0);

		        frame.setVisibility(View.VISIBLE);
		        frame.addView(draggable, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

				return false;*/
               
			}
			
			//*******************Determine the space between the first two fingers
			private float spacing(MotionEvent event) {
			   float x = event.getX(0) - event.getX(1);
			   float y = event.getY(0) - event.getY(1);
			   return FloatMath.sqrt(x * x + y * y);
			}

			//************* Calculate the mid point of the first two fingers 
			private void midPoint(PointF point, MotionEvent event) {
			   float x = event.getX(0) + event.getX(1);
			   float y = event.getY(0) + event.getY(1);
			   point.set(x / 2, y / 2);
			}
			
			public void playSound(int soundid,int loop){
				if (soundid!=0){
				  soundLoop	= loop;
				  soundID = soundPool.load(this, soundid, 1);
				}
			}
			
		/*	public static  boolean onItemLongClickInGamePael(Actor actr) {
				// TODO Auto-generated method stub
				if (state == DRAGGING) {
		            Log.d(TAG, "already have an object moving... ?");
		            return false;
		        }
                
				
				
		        int frame_position[] = new int[2];
		        frame.getLocationOnScreen(frame_position);

		        MainGamePanel.objects.remove(actr);
		        // setup everything for dragging
		        state = DRAGGING;
		        dragged_position = actr.objid;

		        draggable = new ImageView(null);
		        Bitmap bm =null;
		        Drawable dr=Resources.getSystem().getDrawable(MainGamePanel.objects.get(dragged_position).icon);
		        bm=((BitmapDrawable)dr).getBitmap();
		        
		        int wd=bm.getHeight();
		        bm=Bitmap.createScaledBitmap(bm, 50, 50, true);
		        wd=bm.getHeight();
		        draggable.setImageBitmap(bm);
		        //draggable.setScaleType(ImageView.ScaleType.FIT_XY);
		        //draggable.setLayoutParams(new Gallery.LayoutParams(50, 50));
		        //draggable.setMaxWidth(50);
		        //draggable.setMaxHeight(50);
		        draggable.setAlpha(150);
		        draggable.setScaleType(ImageView.ScaleType.CENTER);
		       // draggable.setDrawingCacheEnabled(true);
		        draggable.setPadding((int) current_x-frame_position[0]-(bm.getWidth()/2), (int) current_y-frame_position[1]-(bm.getHeight()/2), 0, 0);

		        frame.setVisibility(View.VISIBLE);
		        frame.addView(draggable, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

				return false;
			}*/
			
			public static void pranesimas(String msg){
				Context context = ctxx;
				CharSequence text = msg;
				int duration = Toast.LENGTH_SHORT;

				Toast toast = Toast.makeText(context, text, duration);
				toast.show();
			}
			public class ImageAdapter extends BaseAdapter {

    			private Context ctx;
    			private List<ObjectHelper> obl=new ArrayList<ObjectHelper>();
    			private int count=0;
    			private int startposition=0;

    			public ImageAdapter(Context c,List<ObjectHelper> obl,int str,int cnt) {
    				ctx = c; 
    				this.obl=obl;
    				count=cnt;
    				startposition=str;
    			}

    			public int getCount() {
                    //int count=obl.size();
    				return this.count;  //objects.pics.length;
    			}

    			public Object getItem(int arg0) {

    				return arg0;
    			}

    			public long getItemId(int arg0) {

    				return arg0;
    			}

    			public View getView(int arg0, View arg1, ViewGroup arg2) {

    				ImageView iView = new ImageView(ctx);
    				iView.setImageResource(obl.get(startposition+arg0).icon);
    				iView.setScaleType(ImageView.ScaleType.FIT_XY);
    				iView.setLayoutParams(new Gallery.LayoutParams(100, 100));//LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT
    				
    			/*	final RelativeLayout borderImg = new RelativeLayout(ctx);
    	            borderImg.setPadding(5, 5, 5, 5);
    	            borderImg.setBackgroundColor(0x88000000);
    	            
    	            final RelativeLayout borderImg1 = new RelativeLayout(ctx);
    	            borderImg1.setPadding(10, 10, 10, 10);
    	            borderImg1.setBackgroundColor(0x88000000);
    	            
    	            borderImg1.addView(iView);
    	            borderImg.addView(borderImg1);*/
    	            //borderImg.addView(iView);

    				return iView;
    			}

    		}
			
			
    		
}

